package com.demo.crm.service;

import com.arvato.crm.common.DynamicQueryUtil;
import com.arvato.crm.model.entity.ManagerLog;
import com.arvato.crm.model.entity.Manager;
import com.demo.crm.model.UserToken;
import com.uaihebert.uaicriteria.UaiCriteria;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import java.util.List;

/**
 * @author tanshuai
 */
@Service
@Slf4j
public class LogService {

    private EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Transactional
    public void log(String summary, HttpServletRequest request) {
        log(summary, null, null, request);
    }

    @Transactional
    public void log(String summary, Object remark, HttpServletRequest request) {
        log(summary, remark, null, request);
    }

    @Transactional
    public void log(String summary, Object remark1, Object remark2, HttpServletRequest request) {
        ManagerLog logInfo = getLog(summary, request);
        if (remark1 != null) {
            logInfo.setRemark1(String.valueOf(remark1));
        }
        if (remark2 != null) {
            logInfo.setRemark2(String.valueOf(remark2));
        }
        saveLog(logInfo);
    }

    public ManagerLog getLog(String summary, HttpServletRequest request) {
        ManagerLog logInfo = new ManagerLog();
        try {
            logInfo.setIp(request.getRemoteAddr());

            UserToken userToken = UserToken.getUserToken(request);
            if (userToken != null) {
                Manager manager = (Manager) userToken.getPrincipal();
                logInfo.setManager(manager);
                logInfo.setManagerName(manager.getName());
            }
            logInfo.setSummary(summary);
        } catch (Exception e) {
            log.error("", e);
        }
        return logInfo;
    }

    public void saveLog(ManagerLog logInfo) {
        try {
            entityManager.persist(logInfo);
        } catch (Exception e) {
            log.error("", e);
        }
    }

    public List<ManagerLog> getByManager(Manager manager) {
        UaiCriteria<ManagerLog> criteria = DynamicQueryUtil.getCriteria(ManagerLog.class);
        criteria.leftJoin("manager").andEquals("manager.id", manager.getId()).orderByDesc("createTime");
        return criteria.getResultList();
    }
}
